package com.sdtv.basemodule.mvp.presenter;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

import com.sdtv.basemodule.mvp.IView;
import com.sdtv.basemodule.rx.RxBus;
import com.sdtv.basemodule.rx.RxBusObserver;

/**
 * @ProjectName: MediunFusion
 * @Package: com.sdtv.basemodule.mvp
 * @ClassName: IPresenter
 * @Description: --mvp -P层的基类
 * @Author: 小郭同学
 * @CreateDate: 2019-06-19 14:51
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public abstract class IPresenter {

    protected AppCompatActivity mContext;

    private IView mView;

    /**
     * 绑定组件
     *
     * @param activity
     * @param view
     */
    public void attachView(AppCompatActivity activity, IView view) {
        this.mContext = activity;
        this.mView = view;
    }

    /**
     * 移除组件
     */
    public abstract void detachView();

    /**
     * 是否绑定了view
     *
     * @return
     */
    public abstract boolean isAttachView();

    /**
     * 移除Presenter
     */
    public void onDestroyPresenter() {
        this.mContext = null;
        detachView();
    }

    /**
     * 创建presenter
     *
     * @param savedState
     */
    public void onCreatePresenter(Bundle savedState) {

    }

    public void onCleared() {

    }

    /**
     * Rxbus观察者 注册
     *
     * @param eventType
     * @param subscriber
     */
    protected void subscribeEvent(final Class<?> eventType, RxBusObserver subscriber) {
        if (mView == null) {
            return;
        }
        RxBus.getInstance().toObservable(eventType)
                .compose(mView.getProvider().bindToLifecycle())
                .subscribe(subscriber);
    }

    /**
     * Rxbus粘性事件观察者
     *
     * @param eventType
     * @param subscriber
     */
    protected void subscribeStickyEvent(final Class<?> eventType, RxBusObserver subscriber) {
        if (mView == null) {
            return;
        }
        RxBus.getInstance().toObservableSticky(eventType)
                .compose(mView.getProvider().bindToLifecycle())
                .subscribe(subscriber);
    }

}
